package cn.bluemobi.app.utils.task;

import java.util.Date;
import java.util.Stack;

/**
 * 任务执行线程
 * 
 * @author mike <br>
 *         2016年1月28日
 * @version 1.0
 */
public class LocalTaskThread implements Runnable {

	private static Stack<Task> taskStack = new Stack<Task>();

	public static boolean isRun = true;

	private static LocalTaskThread instance;

	static long m = 1000 * 60;

	public synchronized static LocalTaskThread newInstance() {
		if (instance == null)
			synchronized (LocalTaskThread.class) {
				if (instance == null)
					instance = new LocalTaskThread();
			}
		return instance;
	}

	private LocalTaskThread() {
		Thread t = new Thread(this);
		t.start();
		System.out.println(">>>>>>>=本地任务线程启动成功");
	}

	public static void addTask(Task task) {
		taskStack.add(task);
	}

	@Override
	public void run() {
		while (isRun) {
			try {
				for (Task syncTask : taskStack) {
					doTask(syncTask);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					Thread.sleep(m);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static void doTask(Task task) throws Exception {
		try {
			System.out.println(">>>>>>>=AT:local - 执行任务      taskId:" + task.getTaskId() + "\t params:" + task.getParams() + "" + new Date());
			ITaskHandler taskHandler = task.getTaskHandler();
			taskHandler.execute(task.getParams(), task.getTaskId());
		} catch (Exception e) {
			taskStack.remove(task);
			throw new Exception(">>>>>>>=AT:local - taskId:" + task.getTaskId() + "\t" + e.getMessage() + "\t" + new Date());
		}
	}
}
